package com.graduation.clientback.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.graduation.clientback.common.R;
import com.graduation.clientback.domain.Material;
import com.graduation.clientback.domain.Work;
import com.graduation.clientback.service.MaterialService;
import com.graduation.clientback.service.WorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private WorkService workService;

    /**
     * 查看材料详情
     * @param workId
     * @return
     */
    @GetMapping("/detail")
    public R<Material> detail(Long workId) {
        LambdaQueryWrapper<Material> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Material::getWorkId, workId);
        Material material = materialService.getOne(queryWrapper);
        return R.success(material);
    }

    /**
     * 提交材料
     * @param material
     * @return
     */
    @Transactional
    @PutMapping("/update")
    public R<String> handleMaterial(@RequestBody Material material) {
        LambdaQueryWrapper<Material> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Material::getWorkId, material.getWorkId());
        Material existMaterial = materialService.getOne(queryWrapper);
        // 不存在
        if(existMaterial == null) {
            material.setCreateTime(LocalDateTime.now());
            material.setUpdateTime(LocalDateTime.now());
            materialService.save(material);
            Work work = workService.getById(material.getWorkId());
            work.setProcess(work.getProcess() + 33);
            workService.updateById(work);
        } else {
            // 存在
//            material.setMaterialId(existMaterial.getMaterialId());
            material.setUpdateTime(LocalDateTime.now());
            materialService.updateById(material);
        }
        return R.success("提交成功");
    }
}
